package com.roncoo.eshop.inventory.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * redis操作工具
 * @author Gao
 */
@Component
public class JedisUtils {

    public static final Logger logger = LoggerFactory.getLogger(JedisUtils.class);

    @Autowired
    private JedisPool jedisPool;

    /******************************以下是对key的操作*********************************/
    /**
     * 获取值
     * @param key
     * @param defaultVal
     */
    public String get(String key, String defaultVal) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String val = jedis.get(key);
            return val == null ? defaultVal : val;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return defaultVal;
    }

    public void set(String key, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String val = jedis.set(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    /**
     * 设置kv ，并制定过期时间
     * @param key
     * @param val
     * @param seconds 有效期（秒）
     */
    public boolean setex(String key, String val, int seconds) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.setex(key, seconds, val);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * 删除key
     *
     * @param key
     */
    public boolean del(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.del(key);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /******************************以下是zset操作*********************************/
    /**
     * 向zset添加元素
     * @param key
     * @param val
     * @param score
     */
    public boolean zadd(String key, long score, String val) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //相同的key, 也只会做更新操作
            jedis.zadd(key, score, val);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * 删除zset元素
     *
     * @param key
     * @param val
     */
    public boolean zdel(String key, String... val) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.zrem(key, val) > 0;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * 获取优先队列元素
     *
     * @param key
     * @param startRange
     * @param endRange
     * @param orderByDesc 是否降序
     */
    public Set<String> getSoredSetByRange(String key, int startRange, int endRange, boolean orderByDesc) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            if (orderByDesc) {
                //降序
                return jedis.zrevrange(key, startRange, endRange);
            } else {
                //升序  按照score进行排序
                return jedis.zrange(key, startRange, endRange);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    /**
     * 获取评分
     * @param key
     * @param member
     */
    public Double getScore(String key, String member) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.zscore(key, member);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    /******************************以下是List操作*********************************/
    /**
     * 获取list长度
     * @param key
     */
    public long countList(String key) {
        if (key == null) {
            return 0;
        }
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.llen(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return 0L;
    }

    /**
     * 添加元素到list（使用右进）
     * @param key
     * @param val
     */
    public boolean insertList(String key, String... val) {
        if (key == null || val == null) {
            return false;
        }
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.rpush(key, val);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * 获取list元素（采用左出方式） 先进先出队列
     *
     * @param key
     * @param start
     * @param end
     */
    public List<String> rangeList(String key, long start, long end) {
        if (key == null || key.equals("")) {
            return null;
        }
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.lrange(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    /**
     * 删除Key中list对应的value值
     * @param key
     * @param values
     * @return
     */
    public int removeListValue(String key, List<String> values) {
        //默认只删除一个元素 重头开始搜索
        return removeListValue(key, 1, values);
    }

    /**
     * 删除list数据
     * @param key
     * @param count
     * @param value
     */
    private boolean removeListValue(String key, long count, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.lrem(key, count, value);
            return true;
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    private int removeListValue(String key, long count, List<String> values) {
        int result = 0;
        if (values != null && values.size() > 0) {
            for (String value : values) {
                if (removeListValue(key, count, value)) {
                    result++;
                }
            }
        }
        return result;
    }
}